package com.yfm;

import org.I0Itec.zkclient.ZkClient;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
@Service
public class DiscoverService implements DiscoverInterface{

   //private String zkAddress;

  // public DiscoverService(String zkAddress){
   //    this.zkAddress = zkAddress;
  // }


    @Override
    public String discover(String name) {
        // 创建 ZooKeeper 客户端
        ZkClient zkClient = new ZkClient("localhost:2181", 5000, 3000);
        System.out.println("1");

        try {
        String servicePath = "/registry"+"/"+name;
        if (!zkClient.exists(servicePath)){
            throw new RuntimeException(String.format("can not find any service node on path: %s", servicePath));
        }
            System.out.println("2");
        List<String> addressList = zkClient.getChildren(servicePath);
        if (addressList.isEmpty()) {
            throw new RuntimeException(String.format("can not find any address node on path: %s", servicePath));
        }
            System.out.println("22");
        String address = addressList.size() == 1? addressList.get(0):addressList.get(ThreadLocalRandom.current().nextInt(addressList.size()));

        String addressPath = servicePath+"/"+address;
        System.out.println("3");

        return  zkClient.readData(addressPath);

    }finally {
        zkClient.close();;
    }




   }
}
